package com.ahui.ydd.controller;

import com.ahui.ydd.common.CustomException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ahui.ydd.common.ResultData;
import com.ahui.ydd.entity.YddCate;
import com.ahui.ydd.service.YddCateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 内容管理--->分类管理
 * @author author
 * @since
 */
@RestController
@RequestMapping("/ydd_cate")
@Slf4j
public class YddCateController {

    @Autowired
    private YddCateService yddCateService;

    /**
     * 添加分类
     * @param yddCate
     * @return
     */
    @PostMapping("/add")
    public ResultData save(@RequestBody YddCate yddCate){
        log.info(yddCate.toString());
        yddCateService.save(yddCate);
        return ResultData.ok("","");
    }
    /**
     * 分页查找
     * @param catename
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData page(String catename, Integer page , Integer limit){
        log.info("page={},pageSize={},name={}",page,limit,catename);

        //构造分页构造器
        Page pageInfo=new Page(page,limit);
        //构造条件构造器
        LambdaQueryWrapper<YddCate> queryWrapper =new LambdaQueryWrapper<>();
        //添加条件过滤
        queryWrapper.like(YddCate::getCatename,catename);

        queryWrapper.orderByAsc(YddCate::getSortNum);
        //执行查询
        yddCateService.page(pageInfo,queryWrapper);
        return ResultData.ok("",pageInfo);
    }

    @GetMapping("/del")
    public ResultData delete(Long id){
        log.info(id.toString());
        int [] arr={3,4,5,6,7,8,9};
        for (int i : arr) {
            if (i == id) {
                throw new CustomException("系统默认数据，不允许删除");
            }
        }
        yddCateService.removeById(id);
        return ResultData.ok("","");
    }

    @GetMapping("/rowInfo")
    public ResultData getById(Long id){
        YddCate yddCate = yddCateService.getById(id);
        if (yddCate != null) {
            return ResultData.ok("",yddCate);
        }
        return ResultData.error("未找到该分类数据");
    }


    @PostMapping("/update")
    public ResultData update(@RequestBody YddCate yddCate){
        log.info(yddCate.toString());
        yddCateService.updateById(yddCate);
        return ResultData.ok("","");
    }

    @GetMapping
    public ResultData allYddCate(){
        List<YddCate> list = yddCateService.list();
        log.info(list.toString());
        return ResultData.ok("",list);
    }
}
